package com.tuxianchao.ssm.aspect;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Web层日志切面
 *
 * @author
 * @create 2018-05-06 18:59
 **/
@Configuration
public class WebLogAspect {
    //TODO 切面输出的日记记录有点问题，需要配置一下log4j
    private Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    // 定义切点Pointcut
    @Pointcut("execution(* com.tuxianchao.ssm.controller.*Controller.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        List<String> params = new ArrayList<>();
        Object[] args = joinPoint.getArgs();
        if (ObjectUtil.isNotNull(args)) {
            for (Object arg : args) {
                if (ObjectUtil.isNotNull(arg)) {
                    params.add(arg.toString());
                }
            }
        } else {
            args = new Object[]{""};
        }

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        startTime.set(System.currentTimeMillis());
        logger.debug("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, CollectionUtil.join(params, ";"));

        // result的值就是被拦截方法的返回值

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        Gson gson = new Gson();
        long endTime = System.currentTimeMillis();
        logger.debug("耗时：{} ，请求结束，的返回值长度是{} ", endTime - startTime.get() + "ms", gson.toJson(ret).length());
    }


    private static String formatDateTime(long timeMillis) {
        long day = timeMillis / (24 * 60 * 60 * 1000);
        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
    }

}
